package com.nf.health.app.mine.fragment;

import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.nf.health.app.R;
import com.nf.health.app.mine.activity.HealthyCurrencyActivity;
import com.nf.health.app.login.activity.LoginActivity;
import com.nf.health.app.activity.global.MainActivity;
import com.nf.health.app.myfamily.activity.MyFamilyActivity;
import com.nf.health.app.mine.activity.MyIntegrationActivity;
import com.nf.health.app.mine.activity.MyhealthActivity;
import com.nf.health.app.mine.activity.PersonalInforActivity;
import com.nf.health.app.mine.activity.SchemeActivity;
import com.nf.health.app.fragment.IBaseFragment;
import com.nf.health.app.mine.activity.SettingActivity;
import com.nf.health.app.activity.doctor_advice.activity.MyDocAdviceActivity;
import com.nf.health.app.activity.my.HourseReponsibilePersionActibity;
import com.nf.health.app.activity.my.MyShopStoreActivity;
import com.nf.health.app.activity.my.SearchDrugStoreActivity;
import com.nf.health.app.activity.my.pay.ScannerPayHistoryActivity;
import com.nf.health.app.healthbank.MyHealthyBankActivity;
import com.nf.health.app.http.Act;
import com.nf.health.app.inquiry.activity.MyInquiryActivity;
import com.nf.health.app.models.ChatMessageVo;
import com.nf.health.app.models.UserInfo;
import com.nf.health.app.utils.ActivityUtils;
import com.nf.health.app.utils.ImageLoaderUtils;
import com.nf.health.app.utils.JsonUtils;
import com.nf.health.app.utils.PreferenceHelper;
import com.nf.health.app.utils.ScreentUtils;
import com.nf.health.app.utils.Util;
import com.nf.health.app.widget.ShowMyDataMineDialog;
import com.nf.health.app.zxing.CaptureActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

public class MainMineFragment extends IBaseFragment implements OnClickListener {

    private static final String GET_INQUIRY_MARK = "get_inquiry_mark";
    //	private View my_dingdan;
//	private View my_money;
    //private View ll_advice;
    private View my_intergation;
    private View ll_health_gold;
    private View rl_wodefangan;
    private View ll_jiankangzhushou;
    private View ll_wodetiwen;

    private View ll_familymember;
    private ImageView user_head_icon;
    private TextView user_nick_name;
    private TextView my_integation;
    private TextView my_healthy_money;
    private View iv_qrcode;
    private View rl_setting;
    private View rl_setting1;
    private View tvUnreadMsg;
    private TextView rl_intehration;
    private View rl_wodeyizhu;
    //	private View iv_head_edit;
    private String url;
    private String usernick;
    private View iv_msg;
    private LinearLayout interation_image, rl_health_money_image;
    private LinearLayout ll_health_bank, ll_shopping_store, ll_scaner_zhangdan;
    private LinearLayout ll_hourse_responsible_persion, ll_medicine_store, ll_scaner_pay;
    private MainActivity mainActivity;

    private TextView titlebar_title_tv;
    LinearLayout ll_container;

    @Override
    public void handleActionStart(String actionName, Object object) {
        //禁止显示Loading
    }

    //yis医生消息条数
    // public void initData() {
//		provider.requestDoctorMsgCount("docMsgCount");
//	}
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        addViewFillInRoot(R.layout.fragment_consult2);
        EventBus.getDefault().register(this);
        initView();
        initListener();
//		String yindao = PreferenceHelper.getString(PreferenceHelper.PERSONALYINDAO, "");
//		if(TextUtils.isEmpty(yindao)){
//			initTipDialog();//显示引导图片
//		}
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            int statusBarHeight = ScreentUtils.getStatusBarHeight(getActivity().getBaseContext());
            ll_container.setPadding(0, statusBarHeight, 0, 0);
            Window window = getActivity().getWindow();
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            //是否显示咨询的小红点
            provider.getInquiryMark(GET_INQUIRY_MARK);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if(!Util.isLogin()){
            return ;
        }
        url = PreferenceHelper.getString(PreferenceHelper.USERICON, "");
        usernick = PreferenceHelper.getString(PreferenceHelper.USERNICK, "");
        //provider.requestMyScore("myscore");//我的积分
        provider.requestUserInfo("userInfo");
        provider.getUserScore(HealthyCurrencyActivity.GET_USER_SCORE);//获取健康币和积分
        loadHeadIcon();

        String yindao = PreferenceHelper.getString(PreferenceHelper.PERSONALYINDAO, "");
        if (TextUtils.isEmpty(yindao)) {
            //使下面按钮无效,防止引导dialog错位显示
            mainActivity = (MainActivity) getActivity();
            mainActivity.makeFootButtonState(false);
            initTipDialog();//显示引导图片
        }
        //是否显示咨询的小红点
        provider.getInquiryMark(GET_INQUIRY_MARK);
        //请求将健康的个数
        provider.getUserHealthMoenyNUm();
    }

    private void initView() {

        titlebar_title_tv = (TextView) rootView.findViewById(R.id.titlebar_title_tv);
//		my_dingdan = rootView.findViewById(R.id.my_dingdan);
//		my_money = rootView.findViewById(R.id.my_money);
//        ll_advice = rootView.findViewById(R.id.ll_advice);
        my_intergation = rootView.findViewById(R.id.my_intergation);
        ll_health_gold = rootView.findViewById(R.id.ll_health_gold);
        rl_wodefangan = rootView.findViewById(R.id.rl_wodefangan);
        ll_jiankangzhushou = rootView.findViewById(R.id.ll_jiankangzhushou);
        ll_familymember = rootView.findViewById(R.id.ll_familymember);
        user_head_icon = (ImageView) rootView.findViewById(R.id.iv_user_head_icon);
        user_nick_name = (TextView) rootView.findViewById(R.id.user_nick_name);
//		iv_head_edit = rootView.findViewById(R.id.iv_head_edit);
        my_integation = (TextView) rootView.findViewById(R.id.my_integation);
        my_healthy_money = (TextView) rootView.findViewById(R.id.my_healthy_money);
        interation_image = (LinearLayout) rootView.findViewById(R.id.rl_intehration_image);
        rl_health_money_image = (LinearLayout) rootView.findViewById(R.id.rl_health_money_image);
        iv_qrcode = rootView.findViewById(R.id.iv_qrcode);
        rl_setting = rootView.findViewById(R.id.rl_setting);
        rl_setting1 = rootView.findViewById(R.id.rl_setting1);
        ll_wodetiwen = rootView.findViewById(R.id.rl_wodetiwen);
        rl_wodeyizhu = rootView.findViewById(R.id.rl_wodeyizhu);
        tvUnreadMsg = rootView.findViewById(R.id.tv_unread_msg_inquiry);
        ll_health_bank = (LinearLayout) rootView.findViewById(R.id.ll_health_bank);
        ll_scaner_zhangdan = (LinearLayout) rootView.findViewById(R.id.ll_scaner_zhangdan);
        ll_shopping_store = (LinearLayout) rootView.findViewById(R.id.ll_shopping_store);
        iv_msg = rootView.findViewById(R.id.iv_msg);
        ll_container = (LinearLayout) rootView.findViewById(R.id.ll_container);
        ll_medicine_store = (LinearLayout) rootView.findViewById(R.id.ll_medicine_store);
        ll_scaner_pay = (LinearLayout) rootView.findViewById(R.id.ll_scaner_pay);
        ll_hourse_responsible_persion = (LinearLayout) rootView.findViewById(R.id.ll_hourse_responsible_persion);
    }

    @Override
    public void handleActionSuccess(String actionName, Object object) {
        if ("userInfo".equals(actionName)) {
            UserInfo userInfo = (UserInfo) object;
            url = userInfo.getHimg();
            usernick = userInfo.getNick();
            loadHeadIcon();
//		}else if("myscore".equals(actionName)){
//			Score score = (Score) object;
//			if(score.getGradeValue() == null || TextUtils.isEmpty(score.getGradeValue())){
//				my_integation.setText("积分:"+0);
//			}else{
//
//			}
        } else if (HealthyCurrencyActivity.GET_USER_SCORE.equals(actionName)) {
            try {
                JSONObject jsonObject = new JSONObject((String) object);
                String healthMoeny = jsonObject.getString("healthMoeny");
                String gradeValue = jsonObject.getString("gradeValue");
                String grade = jsonObject.getString("grade");

                if (!TextUtils.isEmpty(gradeValue)) {
                    PreferenceHelper.putString(PreferenceHelper.GRADE_VALUE, gradeValue);
                    PreferenceHelper.putString(PreferenceHelper.GRADE, grade);
                    my_integation.setText("积分:" + gradeValue);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else if (GET_INQUIRY_MARK.equals(actionName)) {
            //检查问诊红点
            String result = (String) object;
            String isMark = JsonUtils.getFiledData(result, "ismark");
            if ("1".equals(isMark)) {
                tvUnreadMsg.setVisibility(View.VISIBLE);
            } else {
                tvUnreadMsg.setVisibility(View.INVISIBLE);
            }
        } else if (Act.Flag.FLAG_GET_USERHEALTH_MOENY_COUNT.equals(actionName)) {
            String healthMoney = object.toString();
            if (!TextUtils.isEmpty(healthMoney)) {
                PreferenceHelper.putString(PreferenceHelper.HEALTH_MOENY, healthMoney);
                my_healthy_money.setText("健康币:" + healthMoney + "元");
            }
        }
//		else if("docMsgCount".equals(actionName)){
//			if("0".equals(object)){
//				iv_msg.setVisibility(View.GONE);
//			}else{
//				iv_msg.setVisibility(View.VISIBLE);
//			}
//		}
    }

    private void initListener() {
        iv_qrcode.setOnClickListener(this);
        ll_familymember.setOnClickListener(this);
        user_head_icon.setOnClickListener(this);
//		iv_head_edit.setOnClickListener(this);
        interation_image.setOnClickListener(this);
        ll_scaner_zhangdan.setOnClickListener(this);
        rl_health_money_image.setOnClickListener(this);
        rl_wodeyizhu.setOnClickListener(this);
        ll_wodetiwen.setOnClickListener(this);
        rl_setting.setOnClickListener(this);
        rl_setting1.setOnClickListener(this);
//		my_dingdan.setOnClickListener(this);
//		my_money.setOnClickListener(this);
        my_intergation.setOnClickListener(this);
        ll_health_gold.setOnClickListener(this);
        rl_wodefangan.setOnClickListener(this);
        ll_jiankangzhushou.setOnClickListener(this);
        ll_health_bank.setOnClickListener(this);
        ll_shopping_store.setOnClickListener(this);
        ll_hourse_responsible_persion.setOnClickListener(this);
        ll_medicine_store.setOnClickListener(this);
        ll_scaner_pay.setOnClickListener(this);
        ll_scaner_zhangdan.setOnClickListener(this);
        user_nick_name.setOnClickListener(this);//点击名字

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_qrcode:
                ActivityUtils.showActivity(getActivity(), SettingActivity.class);//个人设置
                break;
            case R.id.rl_intehration_image://我的积分
                ActivityUtils.showActivity(getActivity(), MyIntegrationActivity.class);
                break;
            case R.id.rl_health_money_image://健康币
                ActivityUtils.showActivity(getActivity(), HealthyCurrencyActivity.class);
                break;
            case R.id.rl_wodeyizhu://我的医嘱
                ActivityUtils.showActivity(getActivity(), MyDocAdviceActivity.class);
                break;
            case R.id.rl_wodetiwen://我的提问
                ActivityUtils.showActivity(getActivity(), MyInquiryActivity.class);
                break;
            case R.id.ll_familymember:
                ActivityUtils.showActivity(getActivity(), MyFamilyActivity.class);//我的家人
                break;
            case R.id.iv_user_head_icon:
                ActivityUtils.showActivity(getActivity(), PersonalInforActivity.class);//个人资料修改
                break;
            case R.id.ll_hourse_responsible_persion://家庭责任人
                ActivityUtils.showActivity(getActivity(), HourseReponsibilePersionActibity.class);//个人资料修改
                break;
//			case R.id.iv_qrcode:
//				Bundle bundle2 = new Bundle();
//				bundle2.putBoolean("isOpenDocAdviceActivity", true);
//				ActivityUtils.showActivity(getActivity(), CaptureActivity.class, bundle2);//扫一扫
//				break;
//			case R.id.my_dingdan:
//				ActivityUtils.showActivity(getActivity(), OrderActivity.class);//订单
//				break;
//			case R.id.my_money:
//				ActivityUtils.showActivity(getActivity(), WalletActivity.class);//钱包
//				break;

            case R.id.rl_wodefangan:
                ActivityUtils.showActivity(getActivity(), SchemeActivity.class);//我的健康方案
                break;

            case R.id.my_intergation:
                ActivityUtils.showActivity(getActivity(), MyIntegrationActivity.class);//积分
                break;
            case R.id.ll_health_gold:
                ActivityUtils.showActivity(getActivity(), HealthyCurrencyActivity.class);//健康币
                break;

            case R.id.ll_jiankangzhushou:
                ActivityUtils.showActivity(getActivity(), MyhealthActivity.class);//助手
                break;
           /* case R.id.ll_advice:
                ActivityUtils.showActivity(getActivity(), FeedbackActivity.class);//反馈
                break;*/
            case R.id.user_nick_name:
                //是否登录
                if (user_nick_name.getText().equals("登录" + " / " + "注册")) {
                    ActivityUtils.showActivity(getActivity(), LoginActivity.class);
                }
                break;
            case R.id.ll_health_bank://健康银行
                ActivityUtils.showActivity(getActivity(), MyHealthyBankActivity.class);
                break;
            case R.id.ll_shopping_store://我的商城
                //ActivityUtils.showActivity(getActivity(), MyScannerPayActivity.class);
                ActivityUtils.showActivity(getActivity(), MyShopStoreActivity.class);
                break;
            case R.id.ll_scaner_pay://扫码支付
                ActivityUtils.showActivity(getActivity(), CaptureActivity.class);
                break;
            case R.id.ll_medicine_store://药店
                ActivityUtils.showActivity(getActivity(), SearchDrugStoreActivity.class);

                break;
            case R.id.ll_scaner_zhangdan://我的账单
                ActivityUtils.showActivity(getActivity(), ScannerPayHistoryActivity.class);
                break;
        }
    }

    private void loadHeadIcon() {
        if (!TextUtils.isEmpty(url)) {
            ImageLoaderUtils.getinstance(getActivity()).getImage(user_head_icon, url, R.drawable.default_head);
        }
        user_nick_name.setText(usernick);
        if (!checkRegister()) {
            return;
        }
    }

    /**
     * 检测是否已注册
     */
    public boolean checkRegister() {
        String username = PreferenceHelper.getString(PreferenceHelper.USERNAME, "");
        if (!TextUtils.isEmpty(username)) {
            //TODO 测试账号只有3位
            boolean isLogin = PreferenceHelper.getBoolean(PreferenceHelper.ISLOGIN, true);
            if (isLogin) {
                titlebar_title_tv.setText("我的");
                interation_image.setVisibility(View.VISIBLE);
                return isLogin;
            } else {
                user_nick_name.setText("登录" + " / " + "注册");
                interation_image.setVisibility(View.GONE);//未登录积分隐藏
                titlebar_title_tv.setText("我的");
                return isLogin;
            }
        } else {
            user_nick_name.setText("登录" + " / " + "注册");
            interation_image.setVisibility(View.GONE);//未登录积分隐藏
            return false;
        }
    }

    private void initTipDialog() { // 初始化弹出框私人医生
        boolean isLogin = PreferenceHelper.getBoolean(PreferenceHelper.ISLOGIN, false);
        boolean isFinish = isVisible();
        if (isFinish && isLogin) {
            final ShowMyDataMineDialog showMyDataMineDialog = new ShowMyDataMineDialog(getActivity()).showMyPersionDoctor().showDialog();
            showMyDataMineDialog.setMyClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    PreferenceHelper.putString(PreferenceHelper.PERSONALYINDAO, "1");
                    showMyDataMineDialog.dismissDialog();
                    initTipDialog2();
                }
            });
        }

    }

    private void initTipDialog2() { // 初始化弹出框商城
        // TODO Auto-generated method stub
       /* final Dialog dialog = new Dialog(getActivity(), R.style.Dialog_Fullscreen);
        dialog.setCancelable(false);
        dialog.setContentView(R.layout.activity_data_dialog8);
        ImageView iv = (ImageView) dialog.findViewById(R.id.forum_image8);
        iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                mainActivity.makeFootButtonState(true);
            }
        });
        dialog.show();*/
        final ShowMyDataMineDialog showMyDataMineDialog = new ShowMyDataMineDialog(getActivity()).showMyDataShopStoreShop().showDialog();
        showMyDataMineDialog.setMyClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                showMyDataMineDialog.dismissDialog();
                mainActivity.makeFootButtonState(true);
            }
        });

    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    //接收医生发来的消息
    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onDoctorReply(ChatMessageVo message) {
        provider.getInquiryMark(GET_INQUIRY_MARK);
    }
}
